#include"my_stdio.h"
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

static MyFile* BuyFile(int fd, int flag)
{
    MyFile* f =(MyFile*) malloc(sizeof(MyFile));
    if(f == NULL) return NULL;
    f->buffersize = 0;
    f->fileno = fd;
    f->flag = flag;
    f->flush_method = LINE_FLUSH;
    memset(f->buffer, 0, sizeof(f->buffer));
    return f;
}

MyFile* MyFopen(const char* path, const char* mode)
{
  int flag = 0;
  int fd = -1;
    if(strcmp(mode, "w")==0)
    {
       flag = O_CREAT | O_WRONLY | O_TRUNC;
       fd =  open(path, flag, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r") == 0)
    {
        flag = O_RDWR;
        fd = open(path, flag);
    }

    if(fd < 0) return NULL;
    return BuyFile(fd, flag);
}

void MyFclose(MyFile* file)
{
  if(file->fileno < 0) return;
  MyFFlush(file);
  close(file->fileno);
  free(file);
}


void MyFwrite(MyFile* file, void* str, int len)
{
   memcpy(file->buffer+file->buffersize, str, len);
   file->buffersize += len;
   if((file->flush_method & LINE_FLUSH) && file->buffer[file->buffersize - 1] == '\n')
   {
      MyFFlush(file);
   }
}

void MyFFlush(MyFile* file)
{
   if(file->fileno <= 0) return;
   //把数据从用户缓冲器拷贝到内核缓冲器
  int n =  write(file->fileno, file->buffer, file->buffersize);
   (void)n;
   fsync(file->fileno);
   file->buffersize = 0;
}



//<ScrollWheelDown>int main()
//{
//  return 0;
//}
